package com.webwork.lims.stock.service.impl;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.webwork.lims.stock.dao.StockDao;
import com.webwork.lims.stock.dataobject.Stock;
import com.webwork.lims.stock.service.StockService;
import com.webwork.lims.util.Paging;

@Service
public class StockServiceImpl implements StockService {
	
	@Autowired
	private StockDao stockDao;

	@Override
	public int count(Stock queryObj) {
		return stockDao.count(queryObj);
	}

	@Override
	public List<Stock> query(Stock queryObj, Paging paging) {
		return stockDao.query(queryObj, paging.getCurrPage(), paging.getPageSize());
	}
	
	@Override
	public Stock get(String sku) {
		Stock queryObj = new Stock();
		queryObj.setSku(sku);
		List<Stock> order = this.query(queryObj, new Paging(0, 0));
		if (order != null && order.size() > 0) {
			if (order.size() > 1) {
				System.out.println("存在不止一条记录!");
			} else {
				return order.get(0);
			}
		} else {
			System.out.println("找不到该库存!");
		}
		return null;
	}

	@Override
	public void update(Stock stock) {
		stockDao.update(stock);
	}
	
	@Override
	public void insert(Stock stock) {
		stockDao.insert(stock);
	}
	
	@Override
	public Boolean checkStock(String sku, Integer amount) {
		Stock stock = this.get(sku);
		if (amount > stock.getAmount()) {
			return false;
		} else {
			return true;
		}
	}
	
	@Override
	public String useStock(String sku, Integer amount) {
		Stock stock = this.get(sku);
		if (amount > stock.getAmount()) {
			return "notEnough";
		} else {
			stock.setAmount(stock.getAmount() - amount);
			this.update(stock);
			return "enough";
		}
	}
	
	@Override
	public void addStock(String sku, Integer amount) {
		Stock stock = this.get(sku);
		if (stock != null) {
			stock.setAmount(stock.getAmount() + amount);
			this.update(stock);
		} else {
			stock = new Stock();
			stock.setSku(sku);
			stock.setAmount(amount);
			this.insert(stock);
		}
	}

	@Override
	public void delStock(String sku) {
		stockDao.delete(sku);
	}

}
